package com.gua.jbs.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gua.jbs.bean.ProductBean;
import com.gua.jbs.service.IProductService;
import com.gua.jbs.serviceImpl.ProductService;
import com.gua.jbs.utility.ApplicationConstant;
import com.gua.jbs.utility.ApplicationException;
import com.gua.jbs.utility.ExceptionMessage;
import com.gua.jbs.utility.StringUtil;

/**
 * Controller to maintain all purchased products
 * 
 * @author Piyush
 * 
 */
public class PurchaseController extends BaseController {
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String productBarCode = request.getParameter("BARCODE");
		String action = request.getParameter(ApplicationConstant.ACTION);
		if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.SCAN_PRODUCT)) {
			// If BarCode matches with a product
			IProductService productService = new ProductService();
			ProductBean productBean = null;
			try {
				productBean = productService.getProductByCode(productBarCode);
			} catch (ApplicationException ae) {

			}
			if (productBean != null) {
				// Obtain the session object, create a new session if doesn't
				// exist
				HttpSession session = request.getSession(true);

				// Check if our session variable is set, if so, get the session
				// variable value
				// which is an productBean list, add new object to the list.
				// If the value is not set, create a new list and
				// add new object to the list.
				List<ProductBean> productList = (List<ProductBean>) session
						.getAttribute("purchasedProductList");
				if (productList != null) {
					productList.add(productBean);
					session.setAttribute("purchasedProductList", productList);
				} else {
					productList = new ArrayList<ProductBean>();
					productList.add(productBean);
					session.setAttribute("purchasedProductList", productList);
				}
			} else {
				// Error Message : Invalid Bar-Code
				request.setAttribute("exception",
						ExceptionMessage.INVALID_PRODUCT_CODE);
			}
			rd = request.getRequestDispatcher("");
			rd.forward(request, response);

		}
		// Check If user asked for generating bill
		else if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.GENERATE_BILL)) {

		}
	}
}
